import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:screen_brightness/screen_brightness.dart';
import 'package:sports_new/controller/live/qkd_player_logic.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/get_icon.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/live/items/live_share_append.dart';
import 'package:sports_new/view/match_detail/live/live_loading.dart';
import 'package:sports_new/widgets/base/qkd_button.dart';
import 'package:volume_controller/volume_controller.dart';
import '../../../controller/live/ali_live_logic.dart';
import '../../../server/api/other_api.dart';
import '../../../widgets/card.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../../widgets/share/share_sheet.dart';

class LivePanel extends StatefulWidget {
  // final Size viewSize;
  // final Rect texturePos;
  final AliLiveLogic logic;

  const LivePanel({
    super.key,
    required this.logic,
  });

  @override
  State<LivePanel> createState() => _LivePanelState();
}

class _LivePanelState extends State<LivePanel> {
  late final logic = widget.logic;
  late QkdPlayerLogic player =
      Get.find<QkdPlayerLogic>(tag: "${logic.roomInfo?.matchId}");

  Offset startOffset = const Offset(0, 0);
  Offset oldOffset = const Offset(0, 0);
  double _seekPos = -1.0;
  Timer? _hideTimer;
  bool _hideStuff = true;
  final double barHeight = 72;

  @override
  void initState() {
    super.initState();
    _cancelAndRestartTimer();
  }

  @override
  void didChangeDependencies() {
    player.addListener(() {
      try {
        if (mounted) {
          setState(() {});
        }
      } catch (e) {
        Logger().d(e);
      }
    });
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    super.dispose();
    _hideTimer?.cancel();
    VolumeController().removeListener();
  }

  void _startHideTimer() {
    _hideTimer?.cancel();
    _hideTimer = Timer(const Duration(seconds: 3), () {
      setState(() {
        _hideStuff = true;
      });
    });
  }

  void _playOrPause() {
    if (player.status == PlayStatus.started) {
      player.pause();
    } else if (player.status == PlayStatus.paused) {
      player.pauseToPlay();
    } else {
      player.doRefresh();
    }
  }

  void _cancelAndRestartTimer() {
    if (_hideStuff == true) {
      _startHideTimer();
    }
    setState(() {
      _hideStuff = !_hideStuff;
    });
  }

  AnimatedOpacity _buildTopBar(BuildContext context) {
    return AnimatedOpacity(
      opacity: _hideStuff ? 0.0 : 1,
      duration: const Duration(milliseconds: 400),
      child: Container(
        height: barHeight,
        padding: EdgeInsets.only(
            top:
                MediaQuery.of(Get.context!).orientation == Orientation.landscape
                    ? 10
                    : 0,
            left: 10),
        decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Colours.black.withOpacity(0.8), Colors.transparent],
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter)),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              height: 40,
              child: Row(
                children: [
                  IconButton(
                    onPressed: logic.back,
                    icon: Image.asset(
                      Utils.getImgPath('arrow_back.png'),
                      color: Colours.white,
                      width: 24,
                      height: 24,
                    ),
                  ),
                  Container(width: 0),
                  if (logic.matchInfo.hasValue)
                    Expanded(
                      child: QkdText(
                        "${logic.roomInfo?.vtype == 2 ? "回放：" : ""}${logic.matchInfo!}",
                        fontSize: 16,
                        color: Colours.white,
                        needCenter: true,
                        maxLines: 1,
                      ),
                    )
                  else
                    const Spacer(),
                  Container(width: 10),
                  if (MediaQuery.of(Get.context!).orientation ==
                      Orientation.portrait) ...[
                    Block(
                      onTap: logic.dismiss,
                      cardStyle: const CardStyle(
                          color: Colours.transparent,
                          padding: EdgeInsets.only(right: 16)),
                      child: Image.asset(
                        Utils.getImgPath('close_live.png'),
                        color: Colours.white,
                        width: 24,
                        height: 24,
                      ),
                    ),
                    Block(
                      onTap: () async {
                        Utils.onEvent('liveroom_share');
                        Get.bottomSheet(
                            ShareSheet(
                                fromLive: true,
                                append: LiveShareAppend(
                                    liveId: logic.roomId ?? 0,
                                    fromNormal: false)),
                            settings: RouteSettings(
                                arguments: ShareEntity(
                              title: "【直播】这个专家超厉害，快来围观TA的直播",
                              content: "免费比赛分析，尽在球客岛App",
                            )));
                      },
                      cardStyle: const CardStyle(
                          color: Colours.transparent,
                          padding: EdgeInsets.only(right: 16)),
                      child: Image.asset(
                        Utils.getImgPath("live_share.png"),
                        color: Colours.white,
                        width: 24,
                        height: 24,
                      ),
                    ),
                  ],
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  AnimatedOpacity _buildBottomBar(BuildContext context) {
    return AnimatedOpacity(
      opacity: _hideStuff ? 0.0 : 1,
      duration: const Duration(milliseconds: 400),
      child: Container(
        height: barHeight,
        padding: EdgeInsets.only(
            bottom:
                MediaQuery.of(Get.context!).orientation == Orientation.landscape
                    ? 10
                    : 0),
        decoration: BoxDecoration(
            gradient: LinearGradient(
                colors: [Colours.black.withOpacity(0.8), Colors.transparent],
                begin: Alignment.bottomCenter,
                end: Alignment.topCenter)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            SizedBox(
              height: 40,
              child: Row(
                children: <Widget>[
                  IconButton(
                      onPressed: _playOrPause,
                      icon: Icon(
                        player.status == PlayStatus.paused
                            ? GetIcon.pause
                            : GetIcon.play,
                        color: Colours.white,
                        size: 24,
                      )),
                  if (logic.roomInfo?.vtype == 2) ...[
                    QkdText(
                        player.startSlide
                            ? player.formTime()
                            : player.positionTime,
                        fontSize: 12,
                        color: Colours.white),
                    Container(width: 4),
                    Expanded(child: slider()),
                    Container(width: 4),
                    QkdText(player.totalTime,
                        fontSize: 12, color: Colours.white),
                  ] else ...[
                    IconButton(
                      icon: const Icon(GetIcon.refresh, size: 24),
                      onPressed: logic.doRefresh,
                      color: Colours.white,
                      padding: EdgeInsets.zero,
                    ),
                    const Spacer(),
                    const QkdText("切换直播源", color: Colours.white)
                        .tap(logic.changeLive)
                  ],
                  GestureDetector(
                    onTap: () => logic.changeOrientation(),
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      child: Image.asset(
                        Utils.getImgPath('fullscreen_icon.png'),
                        // color: Colours.text,
                        width: 24,
                      ),
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _cancelAndRestartTimer,
      onVerticalDragStart: (details) async {
        if (details.globalPosition.dy < 40) return;
        startOffset = details.globalPosition;
        if (startOffset.dx > Get.width * 5 / 8) {
          player.volumeLevel = 0;
        } else if (startOffset.dx < Get.width * 3 / 8) {
          player.startBrightness = await ScreenBrightness().current;
          player.brightnessLevel = 0;
        }
      },
      onHorizontalDragStart: (details) {
        if (logic.roomInfo?.vtype != 2) return;
        player.startSlide = true;
        player.onSlide = true;
        player.slidePosition = player.currentPosition.toDouble();
        startOffset = details.globalPosition;
      },
      onHorizontalDragUpdate: (details) {
        if (logic.roomInfo?.vtype != 2) return;
        Logger().d(
            "${details.delta.dx / Get.width * 60000} 当前时长：${player.formTime()} 总时长：${player.totalTime}");
        player.slidePosition += details.delta.dx / Get.width * 60000;
      },
      onHorizontalDragEnd: (details) {
        if (logic.roomInfo?.vtype != 2) return;
        player.setPosition();
      },
      onVerticalDragUpdate: (DragUpdateDetails details) async {
        if (details.globalPosition.dy < 40) return;
        if (startOffset.dx > Get.width * 5 / 8) {
          var offset = details.delta - startOffset;
          if (oldOffset.dy.abs() > offset.dy.abs())
            startOffset = details.globalPosition;
          offset = details.globalPosition - startOffset;
          player.onVolumnChanged(offset);
          oldOffset = offset;
        } else if (startOffset.dx < Get.width * 3 / 8) {
          player.onBrightnessChanged(details.globalPosition - startOffset);
        }
      },
      behavior: HitTestBehavior.opaque,
      child: Stack(
        alignment: AlignmentDirectional.center,
        children: [
          if (player.status == PlayStatus.idle ||
              player.status == PlayStatus.prepared ||
              player.status == PlayStatus.initialized) ...[
            Image.asset(
                width: Get.width,
                fit: BoxFit.cover,
                Utils.getImgPath("live_back.png")),
            const Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                LiveLoading(
                  color: Colours.white,
                  size: 44,
                ),
                QkdText("加载中", color: Colours.white)
              ],
            )
          ],
          if (player.status == PlayStatus.error) ...[
            Image.asset(
                width: Get.width,
                fit: BoxFit.cover,
                Utils.getImgPath("live_back.png")),
            Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Expanded(child: Container()),
                QkdText(logic.roomId == 0 ? "信号不稳定，请稍后重试" : "视频加载失败，请稍后重试",
                    color: Colours.white),
                Container(height: 8),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    if (logic.roomId == null && logic.hasAnimate) ...[
                      QkdButton(
                        onPressed: logic.changeToAnimate,
                        // text: "重新连接",
                        backgroundColor: Colours.grey99,
                        widget: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset(
                              Utils.getImgPath('match_detail_animate.png'),
                              width: 16,
                            ),
                            const SizedBox(width: 2),
                            QkdText(
                              '动画直播',
                              color: Colours.white,
                            )
                          ],
                        ),
                        // textStyle: TextStyle(fontSize: 14),
                        width: 92,
                        height: 30,
                        borderRadius: 6,
                      ),
                      const SizedBox(width: 12),
                    ],
                    QkdButton(
                      onPressed: logic.doRefresh,
                      // text: "重新连接",
                      backgroundColor: Colours.main,
                      widget: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(
                            Utils.getImgPath('match_detail_refresh.png'),
                            width: 16,
                          ),
                          QkdText(
                            '点击刷新',
                            color: Colours.white,
                          )
                        ],
                      ),
                      // textStyle: TextStyle(fontSize: 14),
                      width: 92,
                      height: 30,
                      borderRadius: 6,
                    )
                  ],
                ),
                // QkdButton(
                //     onPressed: logic.doRefresh,
                //     text: "重新连接",
                //     textStyle: TextStyle(fontSize: 14),
                //     width: 92,
                //     height: 30,
                //     borderRadius: 6,
                //     foregroundColor: Colours.main,
                //     borderSide:
                //         const BorderSide(color: Colours.main, width: 0.5)),
                Expanded(
                    child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    if (player.errorCode.hasValue)
                      QkdText("[${player.errorCode}]",
                          fontSize: 12, color: Colors.white.withOpacity(0.5)),
                    Container(height: 8)
                  ],
                ))
              ],
            )
          ],
          if (player.status == PlayStatus.completion) ...[
            Image.asset(
                width: Get.width,
                fit: BoxFit.cover,
                Utils.getImgPath("live_back.png")),
            const QkdText("直播已结束", color: Colours.white)
          ],
          if (player.status == PlayStatus.stopped) ...[],
          if (player.startSlide)
            Positioned.fill(
              child: Container(
                  color: Colours.black.withOpacity(0.8),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          QkdText(
                            player.formTime(),
                            fontSize: 20,
                            color: Colours.main,
                            needCenter: true,
                          ),
                          Container(width: 4),
                          QkdText(
                            "/${player.totalTime}",
                            color: Colours.white,
                            needCenter: true,
                          ).paddingOnly(top: 5)
                        ],
                      ),
                      SizedBox(
                        width: 160,
                        child: LinearProgressIndicator(
                          minHeight: 2,
                          value: player.slidePosition / player.duration,
                          valueColor:
                              const AlwaysStoppedAnimation<Color>(Colours.main),
                          backgroundColor: Colours.white.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(13.5),
                        ),
                      )
                    ],
                  )),
            ),
          Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              _buildTopBar(context),
              _buildBottomBar(context),
            ],
          ),
        ],
      ),
    );
  }

  Widget slider() {
    return SliderTheme(
      data: SliderTheme.of(context).copyWith(
        trackHeight: 2,
        trackShape: const RoundedRectSliderTrackShape(),
        activeTrackColor: Colours.main,
        inactiveTrackColor: Colours.white.withOpacity(0.25),
        thumbColor: Colours.white,
        thumbShape: const RoundSliderThumbShape(enabledThumbRadius: 6),
        overlayShape: const RoundSliderOverlayShape(overlayRadius: 6),
        overlayColor: Colours.white.withOpacity(0.5),
      ),
      child: Slider(
        value: player.startSlide
            ? player.slidePosition
            : player.currentPosition.toDouble(),
        max: player.duration.toDouble(),
        allowedInteraction: SliderInteraction.tapAndSlide,
        onChangeStart: (value) {
          player.startSlide = true;
          player.onSlide = true;
          player.slidePosition = value;
        },
        onChanged: (value) => player.slidePosition = value,
        onChangeEnd: (value) => player.setPosition(),
      ),
    );
  }
}
